package com.ygxsk.carhome.ui.leads;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.LeadCarStepStatus;
import com.ygxsk.carhome.enumwrap.LeadCarType;
import com.ygxsk.carhome.enumwrap.LeadGender;
import com.ygxsk.carhome.enumwrap.PermissionsIsSend;
import com.ygxsk.carhome.event.EventLeadDetail;
import com.ygxsk.carhome.event.EventLeadMain;
import com.ygxsk.carhome.listener.ButtonLeadFollowUpListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.LeadDetailItemBean;
import com.ygxsk.carhome.response.LeadListItemBean;
import com.ygxsk.carhome.response.LeadsFollowStepBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.LeadDetailAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.StringCodeUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-11  16:31
 * @Description:潜客详情页面
 */
public class LeadDetailActivity extends ErrorActivity implements EasyPermissions.PermissionCallbacks, ErrorParentExtraSingle {


    //包裹分配按钮和添加记录两个布局
    @BindView(R.id.linearlayouttwobutton)
    LinearLayout linearLayoutTwoButton;

    //添加记录的按钮
    @BindView(R.id.roundtextviewaddrecordlead)
    RoundTextView roundTextViewAddRecord;

    //分配客户的按钮
    @BindView(R.id.roundbuttondistributelead)
    RoundTextView roundButtonDistribute;

    @BindView(R.id.refreshlayoutmanagedetail)
    SmartRefreshLayout refreshLayoutManageDetail;
    //中间的包裹列表
    @BindView(R.id.recyclerviewingroupmanagedetail)
    RecyclerView recyclerViewInGroupManageDetail;

    //有拨打电话的权限内容；
    //扫描二维码需要的部分权限
    private static final int REQUEST_CODE_CALLPHONE_PERMISSIONS = 1;

    //跟进状态的列表时间轴
    private ArrayList<LeadsFollowStepBean> mDataResource = new ArrayList<LeadsFollowStepBean>();
    //适配器内容；
    private LeadDetailAdapter leadDetailAdapter;
    //添加记录的弹窗内容
    private BasePopupView basePopupView_followUp;

    //携带从列表过来的,直接携带过去
    private LeadListItemBean extra_lead_list_item_bean;

    //添加
    private String latentCustomerId_upLoad;

    //拨打电话的字段
    private String leadListItem_call_phone;

    //姓名
    private TextView textViewPersonName;
    //性别
    private TextView textViewPersonSex;
    //年龄
    private TextView textViewPersonYear;
    //手机号
    private TextView textViewPersonPhone;
    //微信号
    private TextView textViewPersonWechat;

    //车主旧车信息的外侧包裹
    private RelativeLayout relativeLayoutOldCarInfo;
    //填充旧车信息
    private TextView textVieCarOldout;

    //车辆品牌
    private TextView textViewCarBrandOut;
    //车辆车系
    private TextView textViewCarSeries;
    //喜好车型
    private TextView textViewPersonCarModelType;
    //客户来源
    private TextView textViewPersonFormWhere;
    //推荐人
    private TextView textViewReferrerPerson;
    //招待顾问
    private TextView textViewReceivePerson;
    //跟进状态
    private TextView textViewLeadStep;
    //预约时间
    private TextView textViewBookingTime;
    //预约的线条
    private TextView textViewLineBookingTime;
    //备注信息，外侧布局，根据备注的是否为空做显示或者隐藏
    private RelativeLayout relativeLayoutRemark;
    //备注文本，填充文字
    private TextView textViewLeadBookingRemark;

    //外侧便于携带的，主要是为了修改潜客信息；
    private LeadDetailItemBean leadDetailItemBean_extraPass;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        //这里有页面刷新，或者编辑完毕，通知页面刷新的逻辑；
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_lead_detail;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setLayoutSao(false, null);
        toolbarHelper.setTitle(getString(R.string.leadcustomdetail));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //checkEdit();
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        //右侧是【编辑】
        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(false, 0, getString(R.string.button_edit_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//
//                //携带 订单的id，获取一次详情，再修改
//
//                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//
//            }
//        });


    }

    @Override
    protected void onClickNodata(View v) {

        //

    }

    @Override
    protected void initViews() {

        //添加纵向布局
        recyclerViewInGroupManageDetail.setLayoutManager(new MyLinearLayoutManager(this));
        recyclerViewInGroupManageDetail.clearAnimation();

        //适配器；
        leadDetailAdapter = new LeadDetailAdapter(R.layout.itemteamerman, mDataResource);
        recyclerViewInGroupManageDetail.setAdapter(leadDetailAdapter);

        //字段内容是 顶部的header内容
        leadDetailAdapter.removeAllHeaderView();
        leadDetailAdapter.addHeaderView(getHeaderView(recyclerViewInGroupManageDetail));
        leadDetailAdapter.setList(mDataResource);

        //有下拉刷新的能力
        refreshLayoutManageDetail.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        //直接清空列表或者列表数据
                        if (mDataResource != null && !mDataResource.isEmpty()) {
                            mDataResource.clear();
                        }

                        //暂时不刷新
//                        if (leadDetailAdapter!=null){
//                            leadDetailAdapter.notifyDataSetChanged();
//                        }

                        gainDatasFromServer();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

        //bug:2024-1-18 14:30:52 携带这个潜客的当前的状态，如果是取消状态，那么没有如下两个按钮的逻辑

        if (extra_lead_list_item_bean != null) {

            int status = extra_lead_list_item_bean.getStatus();
            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "潜客的状态-->" + status);

            if (TextUtils.equals(String.valueOf(status), LeadCarStepStatus.LEAD_STEP_CANCEL_BOOKING.getIndex())) {
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "潜客的状态-->隐藏");
                CommUtils.setViewGone(linearLayoutTwoButton);
            } else {
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "潜客的状态-->显示");
                CommUtils.setViewVisible(linearLayoutTwoButton);
            }
        }

        //分配客户 跳转到人员列表
        if (roundButtonDistribute != null) {
            roundButtonDistribute.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {

                    //跳转到分配人员列表
                    Bundle extra_bundle = new Bundle();
//                    //String shopId = assetInSideBean.getShopId();
//                    //是 从潜客的详情  分配销售  进来的
                    extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_LEAD_DETAIL_ACTIVITY);
                    //携带是新车，还是二手车，
                    extra_bundle.putParcelable(ExtraKey.EXTRA_LEAD_LIST_ITEM_BEAN, extra_lead_list_item_bean);

                    ActivityUtils.startActivity(extra_bundle, LeadManagerGroupActivity.class);

                }
            });
        }

        //底部 【添加记录】的点击事件：
        if (roundTextViewAddRecord != null) {

            roundTextViewAddRecord.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {

                    //当前单据的状态是
                    int currentStatus = 0;

                    if (!TextUtils.isEmpty(leadDetailItemBean_extraPass.getStatus())) {
                        currentStatus = Integer.parseInt(leadDetailItemBean_extraPass.getStatus());
                    }

                    //弹窗有输入框的
                    //弹窗；
                    // TODO: 2023-07-13 11:57 这里的跟进记录要重新开发，暂时传递空值过去
                    //直接弹窗：
                    basePopupView_followUp = new XPopup.Builder(LeadDetailActivity.this)
                            .hasShadowBg(true)
                            //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面;
                            .isViewMode(true)
                            //.autoDismiss(false)
                            //.isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            //.isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                            //.dismissOnTouchOutside(true)
                            //.notDismissWhenTouchInView()
                            //.moveUpToKeyboard(false)
                            .autoFocusEditText(false)//软键盘先不要弹出，当真的要填写原因就弹出。
                            .autoOpenSoftInput(false)//
                            .asCustom(new RecordEditPopu(LeadDetailActivity.this,//
                                    LeadDetailActivity.this,//
                                    ExtraValue.VALUE_JUMP_FORM_LEADDETAILACTIVITY_FOLLOWUP,//
                                    currentStatus,//添加跟进进度的标识；
                                    new ArrayList<>(), //携带当前记录的点击逻辑
                                    new ButtonLeadFollowUpListener() {//

                                        @Override
                                        public void buttonLeadFollowUp(String _status_upLoad, String _remark_upLoad) {

                                            //关闭弹窗，因为这个弹窗会遮盖提交完毕的弹窗；
                                            basePopupView_followUp.dismiss();

                                            CommUtils.checkDialog(mAlertView);
                                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                                    StringUtils.getString(R.string.clearaddorsubmitsuremessage),//提示内容
                                                    StringUtils.getString(R.string.clearcachecancel), //取消
                                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                                    null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                                                @Override
                                                public void onItemClick(Object o, int position) {

                                                    if (position != AlertView.CANCELPOSITION) {

                                                        // 2023-07-13 14:28 点击确定之后，立即调用保存状态接口，并刷新详情接口，
                                                        // bug：2024-1-18 13:46:24 而且还要刷新外侧列表接口，未刷新
                                                        method_upLoadLeadFollowUpStep(_status_upLoad, _remark_upLoad);

                                                    }
                                                }
                                            });

                                            mAlertView.setCancelable(true);
                                            mAlertView.show();
                                        }

                                    }))//
                            .show();
                }
            });
        }


    }


    private View getHeaderView(RecyclerView _recyclerViewWork) {

        View assetManageHeader;

        //2021年12月28日14:54:12 发现是崩溃的日志内容：
        // java.lang.NullPointerException: Attempt to invoke virtual method
        // 'android.view.ViewParent androidx.recyclerview.widget.RecyclerView.getParent()' on a null object reference
        if ((_recyclerViewWork != null) && (_recyclerViewWork.getParent() != null)) {
            assetManageHeader = LayoutInflater.from(LeadDetailActivity.this).inflate(//
                    R.layout.leaddetailsubmitheader, //
                    (ViewGroup) _recyclerViewWork.getParent(),//
                    false);//
        } else {
            assetManageHeader = LayoutInflater.from(LeadDetailActivity.this).inflate(R.layout.leaddetailsubmitheader, null);
        }

        //添加布局内容；
        //编辑 潜客顶部信息
        RoundTextView roundTextViewEditLeadInfoRight = (RoundTextView) assetManageHeader.findViewById(R.id.roundtextvieweditleadinforight);
        //姓名
        textViewPersonName = (TextView) assetManageHeader.findViewById(R.id.textviewpersonname);
        //性别
        textViewPersonSex = (TextView) assetManageHeader.findViewById(R.id.textviewpersonsex);
        //年龄
        textViewPersonYear = (TextView) assetManageHeader.findViewById(R.id.textviewpersonyear);

        //电话号码外侧的布局内容：
        RelativeLayout layoutPhoneWrapContent = (RelativeLayout) assetManageHeader.findViewById(R.id.layoutphonewrapcontent);

        //手机号
        textViewPersonPhone = (TextView) assetManageHeader.findViewById(R.id.textviewpersonphone);
        //微信号
        textViewPersonWechat = (TextView) assetManageHeader.findViewById(R.id.textviewpersonwechat);

        //车主旧车，默认是隐藏的，如果用户的是旧车就展示出来
        relativeLayoutOldCarInfo = (RelativeLayout) assetManageHeader.findViewById(R.id.relativelayoutoldcarinfo);
        textVieCarOldout = (TextView) assetManageHeader.findViewById(R.id.textviecaroldout);

        //车辆品牌
        textViewCarBrandOut = (TextView) assetManageHeader.findViewById(R.id.textviecarbrandout);
        //车辆系列
        textViewCarSeries = (TextView) assetManageHeader.findViewById(R.id.textviecarseries);
        //喜好车型
        textViewPersonCarModelType = (TextView) assetManageHeader.findViewById(R.id.textviewpersoncartype);
        //客户来源
        textViewPersonFormWhere = (TextView) assetManageHeader.findViewById(R.id.textviewpersonformwhere);
        //推荐人
        textViewReferrerPerson = (TextView) assetManageHeader.findViewById(R.id.textviewreferrerperson);
        //接待顾问
        textViewReceivePerson = (TextView) assetManageHeader.findViewById(R.id.textviewreceiveperson);
        //跟进状态
        textViewLeadStep = (TextView) assetManageHeader.findViewById(R.id.textviewleadstep);
        //预约时间
        textViewBookingTime = (TextView) assetManageHeader.findViewById(R.id.textviewbookingtime);
        //备注信息
        //如果备注信息有，就展示，没有就隐藏
        textViewLineBookingTime = (TextView) assetManageHeader.findViewById(R.id.textviewlinebookingtime);
        relativeLayoutRemark = (RelativeLayout) assetManageHeader.findViewById(R.id.relativelayoutremark);
        textViewLeadBookingRemark = (TextView) assetManageHeader.findViewById(R.id.textviewleadbookingremark);

        //filldatas

        //潜客的【编辑】逻辑；
        if (roundTextViewEditLeadInfoRight != null) {
            roundTextViewEditLeadInfoRight.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {

                    //携带客户信息-到 添加潜客页面
                    Bundle extra_bundle = new Bundle();
                    //携带详情数据
                    if (leadDetailItemBean_extraPass != null) {

                        //添加 携带是从【修改 潜客】过去的
                        extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_LEAD_MODIFY);

                        extra_bundle.putParcelable(ExtraKey.EXTRA_LEAD_DETAIL_ITEM_BEAN, leadDetailItemBean_extraPass);

                        ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);

                    } else {
                        ToastUtils.showShort(getString(R.string.action_abnormal));
                    }

                }
            });
        }

        //....
        //电话拨打权限 ：
        if (layoutPhoneWrapContent != null) {
            layoutPhoneWrapContent.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {
                    clickButton_toCallPhone(mActivityInstance, leadListItem_call_phone, CallHistoryBusinessType.BUSINESSTYPE_1.getIndex());
                }
            });
        }
        return assetManageHeader;

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            gainDatasFromServer();

        } else {
            //遮盖信息
            netWorkError();
        }

    }

    @AfterPermissionGranted(REQUEST_CODE_CALLPHONE_PERMISSIONS)
    private void requestCodeCallPhonePermissions() {

//        String[] perms = {Manifest.permission.CALL_PHONE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        String[] perms = {Manifest.permission.CALL_PHONE};

        if (!EasyPermissions.hasPermissions(this, perms)) {

            //如果没有这两个权限，
            EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.callphonerequestpermissions), REQUEST_CODE_CALLPHONE_PERMISSIONS, perms);

        } else {
            //直接拨打逻辑
//            clickButton_toCallPhone(mActivityInstance, leadListItem_call_phone);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        //同意权限之后的操作；放在了【AfterPermissionGranted】之中

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        //未同意权限的操作
//        if (requestCode == PRC_PHOTO_PICKER) {
//            //Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
//            ToastUtils.showShort("您拒绝了「图片选择」所需要的相关权限!");
//        } else

        if (requestCode == REQUEST_CODE_CALLPHONE_PERMISSIONS) {
            //拒绝了拨打电话的权限
            ToastUtils.showShort(R.string.refuse_callphone_permissions);
        }

    }

    //直接拨打电话的能力
//    private void clickButton_toCallPhone(Activity _activity, String mPhoneNumber) {
//
//        CommUtils.checkDialog(mAlertView);
//
//        //二次确认弹窗提示
//        mAlertView = new AlertView(ConstantSign.ALERTVIEW_TITLE_FOR_PHONE,//
//                mPhoneNumber, //
//                ConstantSign.ALERTVIEW_LEFT_CANCEL,//
//                new String[]{ConstantSign.ALERTVIEW_RIGHT_COPY_INFORMATION}, //
//                null, //
//                _activity, //
//                AlertView.Style.Alert,//
//                new OnItemClickListener() {
//                    @Override
//                    public void onItemClick(Object o, int position) {
//
//                        if (position != AlertView.CANCELPOSITION) {
//
//                            if (!TextUtils.isEmpty(mPhoneNumber)) {
//                                _activity.startActivity(CommUtils.callThePhoneNumAction_dial(mPhoneNumber));
//                            } else {
//                                ToastUtils.showShort(R.string.hasfailgetphonenumber);
//                            }
//
//                        }
//                    }
//                }
//        );
//
//        mAlertView.setCancelable(true).show();
//
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInLeadDetail(EventLeadDetail eventLeadDetail) {

        if (eventLeadDetail != null) {

            if (eventLeadDetail.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_LEAD_DETAIL) {

                //清空历史数据
                if (mDataResource != null && !mDataResource.isEmpty()) {
                    mDataResource.clear();
                }

                //隐式的刷新；
                if (leadDetailAdapter != null) {
                    leadDetailAdapter.notifyDataSetChanged();
                }

                gainDatasFromServer();

            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        CommUtils.checkDialog(mAlertView);

        if (mDataResource != null && !mDataResource.isEmpty()) {
            mDataResource.clear();
        }

        if (leadDetailAdapter != null) {
            leadDetailAdapter.notifyDataSetChanged();
            leadDetailAdapter = null;
        }

        mDataResource = null;

        if (basePopupView_followUp != null) {
            basePopupView_followUp.onDestroy();
            basePopupView_followUp = null;
        }

        if (leadDetailItemBean_extraPass != null) {
            leadDetailItemBean_extraPass = null;
        }

        //注销监听
        EventBus.getDefault().unregister(this);

    }


    //添加跟进进度，或者是取消这个潜客预约 取消预约。
    private void method_upLoadLeadFollowUpStep(String status_upLoad, String remark_upLoad) {

        //
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.latentCustomerId, latentCustomerId_upLoad);//潜客主键ID
        map.put(Parameterkey.status, status_upLoad);//进度状态
        map.put(Parameterkey.remark, remark_upLoad);//备注

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDLATENTRECORD_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addLatentRecord_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .addLatentRecord(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(LeadDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String value) throws Throwable {

//                        {
//                                "code":"20000",
//                                "data":1,
//                                "message":"success"
//                        }

                        //通知外侧潜客列表接口刷新：
                        EventLeadMain eventLeadMain = new EventLeadMain();
                        eventLeadMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_LEADMAINLIST);
                        EventBus.getDefault().post(eventLeadMain);


                        CommUtils.checkMaterialDialog(materialDialog);

                        //提交完毕给提示的
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //
                                getString(R.string.add_submit_success), //
                                null, //
                                null, //
                                null, //
                                LeadDetailActivity.this, //
                                AlertView.Style.Alert, //
                                null);
                        mAlertView.setCancelable(true).show();//

                        mCompositeDisposable.add(Observable.timer(ConstantApi.ALERTVIEW_TIME_DELAY, TimeUnit.MILLISECONDS)
                                .subscribeOn(AndroidSchedulers.mainThread())//
                                .observeOn(AndroidSchedulers.mainThread())//
                                .compose(LeadDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                                .subscribe(new Consumer<Long>() {
                                    @Override
                                    public void accept(Long aLong) throws Exception {

                                        if (mAlertView != null) {
                                            if (mAlertView.isShowing()) {
                                                mAlertView.dismiss();
                                                mAlertView = null;
                                            }
                                        }

                                        //刷新接口信息
                                        gainDatasFromServer();

                                    }
                                }));
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                });
    }

    private void gainDatasFromServer() {

        latentCustomerId_upLoad = extra_lead_list_item_bean.getLatentCustomerId();

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.latentCustomerId, latentCustomerId_upLoad);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETBYID_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getById_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_GET);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                //.getById(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                .getById(latentCustomerId_upLoad)
                .compose(LeadDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<LeadDetailItemBean>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).subscribe(new Consumer<LeadDetailItemBean>() {
                    @Override
                    public void accept(LeadDetailItemBean leadDetailItemBean) throws Throwable {

                        //主要是顶部变动
                        if (leadDetailItemBean != null) {

                            //外侧携带 修改 潜客 信息
                            leadDetailItemBean_extraPass = leadDetailItemBean;

                            //重新更新 这个id
                            latentCustomerId_upLoad = leadDetailItemBean.getLatentCustomerId();

                            //重新设置两个重要的值内容
                            extra_lead_list_item_bean.setLatentCustomerId(leadDetailItemBean.getLatentCustomerId());

                            //是新车还是二手车，涉及到分配 给销售人员，是分配给新车销售还是二手车销售
                            extra_lead_list_item_bean.setLatentType(leadDetailItemBean.getLatentType());

                            //判断车辆的类型：是新车或者旧车 类型，如果是旧车，要展示旧车完整信息
                            String latentType = leadDetailItemBean.getLatentType();


                            //头部信息挨个填充
                            Delivery.getInstance().post(new Runnable() {
                                @Override
                                public void run() {

                                    //姓名
                                    CommUtils.setText(textViewPersonName, leadDetailItemBean.getCustomerName());
                                    //手机号
                                    leadListItem_call_phone = leadDetailItemBean.getCustomerPhone();
//                                    CommUtils.setText(textViewPersonPhone, leadDetailItemBean.getCustomerPhone());
                                    CommUtils.setText(textViewPersonPhone, StringCodeUtils.mobileEncrypt(leadDetailItemBean.getCustomerPhone()));

                                    //性别 memberSex "memberSex": "", //性别：1男、2女、3保密
                                    if (TextUtils.equals(LeadGender.LEAD_GENDER_MEN.getIndex(), leadDetailItemBean.getMemberSex())) {
                                        CommUtils.setText(textViewPersonSex, LeadGender.LEAD_GENDER_MEN.getValue());//男士
                                    } else if (TextUtils.equals(LeadGender.LEAD_GENDER_WOMEN.getIndex(), leadDetailItemBean.getMemberSex())) {
                                        CommUtils.setText(textViewPersonSex, LeadGender.LEAD_GENDER_WOMEN.getValue());//女士
                                    } else if (TextUtils.equals(LeadGender.LEAD_GENDER_UNKNOW.getIndex(), leadDetailItemBean.getMemberSex())) {
                                        CommUtils.setText(textViewPersonSex, LeadGender.LEAD_GENDER_UNKNOW.getValue());//未知
                                    } else {
                                        //如果是0 ，不是以上任何信息，那么就不展示，展示空值
                                        CommUtils.setText(textViewPersonSex, "");
                                    }

                                    //年龄信息
                                    CommUtils.setText(textViewPersonYear, leadDetailItemBean.getAgeNum());
                                    //微信号
                                    CommUtils.setText(textViewPersonWechat, leadDetailItemBean.getWeChat());

                                    //如果是旧车信息，那么展示旧车
//                                    public enum LeadCarType {
//                                        LEADTYPE_CAR_NEW("1", "新车"),
//                                        LEADTYPE_CAR_OLD("2", "二手车");

                                    if (TextUtils.equals(latentType, LeadCarType.LEADTYPE_CAR_NEW.getIndex())) {

                                        if (relativeLayoutOldCarInfo != null) {
                                            relativeLayoutOldCarInfo.setVisibility(View.GONE);
                                        }

                                        if (textVieCarOldout != null) {
                                            textVieCarOldout.setText("");
                                        }

                                    } else if (TextUtils.equals(latentType, LeadCarType.LEADTYPE_CAR_OLD.getIndex())) {

                                        if (relativeLayoutOldCarInfo != null) {
                                            relativeLayoutOldCarInfo.setVisibility(View.VISIBLE);
                                        }

                                        if (textVieCarOldout != null) {
                                            textVieCarOldout.setText(leadDetailItemBean.getOldCarRemark());
                                        }

                                    }

                                    //车辆品牌
                                    CommUtils.setText(textViewCarBrandOut, leadDetailItemBean.getCarBrandName());
                                    //车辆车系
                                    CommUtils.setText(textViewCarSeries, leadDetailItemBean.getCarSeriesName());
                                    //喜好车型
                                    CommUtils.setText(textViewPersonCarModelType, leadDetailItemBean.getVehicleName());
                                    //客户来源
                                    CommUtils.setText(textViewPersonFormWhere, leadDetailItemBean.getCreatesourceName());
                                    //推荐人
                                    //2023-08-08 11:09 推荐人和招待顾问空白  recommendName推荐人
                                    CommUtils.setText(textViewReferrerPerson, leadDetailItemBean.getRecommendName());
                                    //招待顾问 receptionName接待顾问
                                    CommUtils.setText(textViewReceivePerson, leadDetailItemBean.getReceptionName());
                                    //跟进状态
                                    CommUtils.setText(textViewLeadStep, leadDetailItemBean.getStatusName());
                                    //预约时间
                                    CommUtils.setText(textViewBookingTime, leadDetailItemBean.getAppointedDay());
                                    //备注信息
                                    String remark = leadDetailItemBean.getRemark();

                                    if (!TextUtils.isEmpty(remark)) {
                                        relativeLayoutRemark.setVisibility(View.VISIBLE);
                                        textViewLineBookingTime.setVisibility(View.VISIBLE);
                                        CommUtils.setText(textViewLeadBookingRemark, leadDetailItemBean.getRemark());
                                    } else {
                                        relativeLayoutRemark.setVisibility(View.GONE);
                                        textViewLineBookingTime.setVisibility(View.GONE);
                                        CommUtils.setText(textViewLeadBookingRemark, "");
                                    }

                                    //处理【分配客户】的按钮
                                    int isSend = leadDetailItemBean.getIsSend();
                                    if (isSend == PermissionsIsSend.IS_SEND_CAN.getIndex()) {
                                        roundButtonDistribute.setVisibility(View.VISIBLE);
                                    } else if (isSend == PermissionsIsSend.IS_SEND_NOT.getIndex()) {
                                        roundButtonDistribute.setVisibility(View.GONE);
                                    }

                                }
                            });

                            //底部列表适配器的填充
                            ArrayList<LeadsFollowStepBean> latentRecordVoList = leadDetailItemBean.getLatentRecordVoList();

                            if (mDataResource != null && !mDataResource.isEmpty()) {
                                mDataResource.clear();
                            }

                            if (latentRecordVoList != null && !latentRecordVoList.isEmpty()) {
                                if (mDataResource != null) {
                                    mDataResource.addAll(latentRecordVoList);
                                }
                            }

                            //同时刷新适配器
                            if (leadDetailAdapter != null) {
                                leadDetailAdapter.notifyDataSetChanged();
                            }

                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        function_apiException(apiException);

                    }
                });

    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }


    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);
            extra_lead_list_item_bean = bundle.getParcelable(ExtraKey.EXTRA_LEAD_LIST_ITEM_BEAN);

        }

    }
}